package cn.wolfcode.shop.service;

import cn.wolfcode.shop.domain.UserInfo;
import cn.wolfcode.shop.domain.UserLogin;
import cn.wolfcode.shop.exception.UserException;
import cn.wolfcode.shop.mapper.UserInfoMapper;
import cn.wolfcode.shop.mapper.UserLoginMapper;
import cn.wolfcode.util.RedisConstants;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import java.net.URLDecoder;
import java.sql.Time;
import java.text.MessageFormat;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class UserLoginServiceImpl implements IUserLoginService {

    @Autowired
    private UserLoginMapper userLoginMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserInfoMapper userInfoMapper;

    @Override
    public UserLogin register(String username, String password) {
        int count = userLoginMapper.getCountByUsername(username);

        if (count > 0) {
            throw new UserException("该用户名已注册,请重新输入");
        } else {

            UserLogin userLogin = new UserLogin();
            userLogin.setUserName(username);
            userLogin.setPassword(password);

            userLoginMapper.insert(userLogin);
            //保存用户信息
            UserInfo userInfo = new UserInfo();
            userInfo.setId(userLogin.getId());
            userInfoMapper.insert(userInfo);
            return userLogin;
        }

    }

    @Override
    public String login(String username, String password) {
        UserLogin userLogin = userLoginMapper.login(username, password);
        if (userLogin == null) {
            throw new UserException("登录名或密码有误");
        }
        //获取token
        String token = creatToken(userLogin);

        return token;
    }


    //生成token
    public String creatToken(UserLogin userLogin) {

        String token = UUID.randomUUID().toString();
        System.out.println(token);
        String key = MessageFormat.format(RedisConstants.USER_TOKEN, token);
        System.out.println(key);
        redisTemplate.opsForValue().set(key, userLogin);
        //设置key的有效时间
        redisTemplate.expire(key, 30, TimeUnit.DAYS);

        return token;
    }


    @Override
    public void logout(String token) {

        String key = MessageFormat.format(RedisConstants.USER_TOKEN, token);
        redisTemplate.delete(key);

    }
}
